package com.blindnetworking;

import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.google.appengine.api.datastore.Entity;

public class MailUtil {

	static Pattern emailPattern = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");

	public static boolean isValidEmailAddress(String email) {
		Matcher m = emailPattern.matcher(email); return !m.matches();
	}
	
	public static void sendMail(String name, String email, String subject, String body) throws Exception{
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("networkingblind@gmail.com", "Blind Networking"));
        msg.addRecipient(Message.RecipientType.TO,
                         new InternetAddress(email, name));
        msg.setSubject(subject);
        
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
            mp.addBodyPart(htmlPart);
            msg.setContent(mp);
        
        Transport.send(msg);
	}

	public static void sendWelcomeMail(String name, String email) throws Exception {
		StringBuilder body = new StringBuilder();
		body.append("Hello ").append(name).append("!<br/><br/>");
		body.append("Your registration was completed sucessfully. Soon you will receive your first invite to a blind date.<br/><br/>");
		body.append("<bold>How does it work?<bold><br/>");
		body.append(" - The super specialized random algoritms in our server will select periodically two participants.<br/>");
		body.append(" - Each selected participant will recieve an invitation with the proposed time of the meeting.<br/>");
		body.append(" - The participants can then ACCEPT or DECLINE the invitation. <br/>");
		body.append(" - If both participants accept the date, we will send each one the first name of the date partner, and what he or she is wearing.<br/>");
		body.append(" - You will then meet in the selected venue at the specified time. Please show up and dont be late!<br/>");
		
		body.append("<br/><br/><br/>HAPPY NETWORKING!");
		
		sendMail(name, email, "Registration | Blind Networking", body.toString());
		
	}

	public static void sendConfirmationMails(Entity u1, Entity u2, Entity meeting) throws Exception{
		sendConfirmationEmail(u1, meeting, (String)meeting.getProperty("user1ConfirmKey"));
		sendConfirmationEmail(u2, meeting, (String)meeting.getProperty("user2ConfirmKey"));
	}
	
	private static void sendConfirmationEmail(Entity user, Entity meeting, String confirmKey) throws Exception{
		StringBuilder body = new StringBuilder();
		body.append("Hello ").append(user.getProperty("name")).append("!<br/><br/>");
		
		body.append("You have been selected for a new blind date:<br/>");
		body.append(" - Date: ").append((Date)meeting.getProperty("meetingDate")).append("<br/>");
		body.append(" - Venue: ").append((String)meeting.getProperty("venue")).append("<br/>");
		
		body.append("<br/>Do you acceppt this networking oportunity? <br/>");
		
		String acceptUrl="http://blind-networking.appspot.com/accept?key=" + confirmKey;
		String declineUrl="http://blind-networking.appspot.com/decline?key=" + confirmKey;
		
		body.append("<a href=\"");
		body.append(acceptUrl);
		body.append("\"> ACCEPT</a>");
		
		body.append(" | ");
		
		body.append("<a href=\"");
		body.append(declineUrl);
		body.append("\"> DECLINE</a>");
		
		body.append("<br/><br/>You have ").append(Consts.MINUTES_TO_REPLY_INVITATION).append(" minutes to reply to this invitation.");
		body.append("<br/>If you or your partner do not respond or decline, the date will be canceled and you will both loose this networking oportunity.");
		
		body.append("<br/><br/><br/>HAPPY NETWORKING!");
		
		sendMail((String)user.getProperty("name"), (String)user.getProperty("email"), "New networking oportunity!", body.toString());
	}

	public static void sendFinalConfirmationEmails(Entity u1, Entity u2,
			Entity meeting) throws Exception {

		sendFinalConfirmationEmail(u1, u2, meeting);
		sendFinalConfirmationEmail(u2, u1, meeting);
		
	}

	private static void sendFinalConfirmationEmail(Entity user, Entity partner, Entity meeting) throws Exception{

		StringBuilder body = new StringBuilder();
		body.append("Hello ").append(user.getProperty("name")).append("!<br/><br/>");
		
		body.append("Your blind date is confirmed:<br/>");
		body.append(" - Your partner: ").append(partner.getProperty("name")).append("<br/>");
		body.append(" - Date: ").append((Date)meeting.getProperty("meetingDate")).append("<br/>");
		body.append(" - Venue: ").append((String)meeting.getProperty("venue")).append("<br/>");
		body.append(" - Conversation Starter: ").append((String)meeting.getProperty("starter")).append("<br/>");

		body.append("<br/><br/><br/>HAPPY NETWORKING!");

		sendMail((String)user.getProperty("name"), (String)user.getProperty("email"), "Blind date Confirmed!!", body.toString());

	}
	
}
